<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
/*
	数据库操作函数
 */
namespace core;
defined('BY_JYA') or exit('error');
class url_diy{
	public function config($type){
		$config_file=ROOT_D.'/core/'.($type==1?'manage':'custom').'.url.config.php';
		if(is_file($config_file)){
			$url_config=require($config_file);
		}else{
			$url_config=pdo_getall('core_url_config',array('this'=>$type,'status'=>1),array('diy','common'),'','display desc');
		}
		return $url_config;
	}
	public function decode($gets,$type=1){
		//将自定义URL映射为普通URL
		$url_config=$this->config($type);
		if(empty($url_config)){
			return $gets;
		}
		$gets_array=explode('/',$gets);
		$gets_count=count($gets_array);
		foreach($url_config as $rule){
			$temp=explode('/',$rule['diy']);
			$pair=true;
			if( count($temp) == $gets_count){
				foreach($temp as $index=>$value){
					if(substr($value,0,1)!=':' && $value!=$gets_array[$index]){
						$pair=false;
						break;
					}
				}
			}else{
				$pair=false;
			}
			if($pair){
				break;
			}
		}
		if($pair){
			//匹配到合适规则，根据规则读取请求参数
			$query=array();
			$temp=explode('/',$rule['diy']);
			foreach($temp as $index=>$value){
				if(substr($value,0,1)==':'){
					//取出对应位置变量
					$key=substr($value,1);
					$value=$gets_array[$index];
					$query[$key]=$value;
				}
			}
			$query=http_build_query($query);
			
			$gets=links($rule['common']);
			if($gets['query']){
				$gets['query'].='&'.$query;
			}else{
				$gets['query']=$query;
			}
			
			$gets="{$gets['plugin']}/{$gets['action']}/{$gets['op']}/{$gets['query']}";
		}
		return $gets;
	}
	/*
		将普通URL映射为自定义URL
		检查是否存在合适规则
		如果有合适规则，根据规则转换为自定义URL
	*/
	public function encode($url_string,$type=1){
		$url_config=$this->config($type);
		if(empty($url_config)){
			//无自定义规则，直接返回原始串
			return $url_string;
		}
		
		foreach($url_config as $rule){
			$temp=links($rule['common'],true);
			$url_array=links($url_string,true);
			$pair=true;
			if($temp['plugin']==$url_array['plugin'] && $temp['action']==$url_array['action'] && $temp['op']==$url_array['op']){
				//以上三项正确，再比较请求参数
				foreach($temp['query'] as $key=>$value){
					if($url_array['query'][$key]!=$value){
						//某项请求参数不一致，则不匹配
						$pair=false;
						break;
					}else{
						unset($url_array['query'][$key]);
					}
				}
				//请求参数正确，再检查是否存在参数溢出
				$rule['diy']=explode('/',$rule['diy']);
				foreach($url_array['query'] as $key=>$value){
					$key=':'.$key;
					if(!in_array($key,$rule['diy'])){
						$pair=false;
						break;
					}
				}
			}else{
				$pair=false;
			}
			if($pair){
				//完全匹配
				$right=$rule;
				break;
			}
		}
		if($pair){
			//得出匹配规则。根据匹配规则生成自定义URL
			//替换自定义URL中的变量
			foreach($rule['diy'] as &$row){
				if(substr($row,0,1)==':'){
					$key=substr($row,1);
					$row=$url_array['query'][$key];
				}
			}
			$diy_string=implode('/',$rule['diy']);
			return $diy_string;
		}else{
			//无匹配规则，返回原始串
			return $url_string;
		}
	}
}